package com.example.lcode.backtrack;

import java.util.*;

public class Question17 {

    public List<String> letterCombinations(String digits) {
        Map<String, List<String>> map = new HashMap<>();
        map.put("1", new ArrayList<>());
        map.put("2", Arrays.asList("a", "b", "c"));
        map.put("3", Arrays.asList("d", "e", "f"));
        map.put("4", Arrays.asList("g", "h", "i"));
        map.put("5", Arrays.asList("j", "k", "l"));
        map.put("6", Arrays.asList("m", "n", "o"));
        map.put("7", Arrays.asList("p", "q", "r", "s"));
        map.put("8", Arrays.asList("t", "u", "v"));
        map.put("9", Arrays.asList("w", "x", "y", "z"));
        List<String> res = new ArrayList<>();
        if (digits == null || digits.length() == 0) {
            return res;
        }
        List<String> letterCombinations = getLetterCombinations(map, digits, 0, res, new StringBuilder(""));
        return letterCombinations;
    }

    private List<String> getLetterCombinations(Map<String, List<String>> map, String digits, int index, List<String> res, StringBuilder str) {
        if (index == digits.length()) {
            res.add(str.toString());
            return res;
        }
        List<String> strs = map.get(digits.substring(index, index + 1));
        for (int i = 0; i < strs.size(); i++) {
            str = str.append(strs.get(i));
            getLetterCombinations(map, digits, index + 1, res, str);
            str.delete(str.length() - 1, str.length());
        }
        return res;
    }

    public static void main(String[] args) {
        Question17 question17 = new Question17();
        List<String> list = question17.letterCombinations("23");
        System.out.println(list);
    }

}
